package com.hmdp.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private static final String CACHE_SHOP_TYPE_KEY = "cache:shopType:list";

    @Override
    public List<ShopType> queryTypeList() {
        String json = stringRedisTemplate.opsForValue().get(CACHE_SHOP_TYPE_KEY);
        if (json != null && !json.isEmpty()) {
            return JSON.parseArray(json, ShopType.class);
        }

        QueryWrapper<ShopType> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByAsc("sort");
        // 这里调用的是 ServiceImpl 中提供的 list 方法
        List<ShopType> typeList = this.list(queryWrapper);
        if (typeList == null || typeList.isEmpty()) {
            return new ArrayList<>();
        }

        json = JSON.toJSONString(typeList);
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_TYPE_KEY, json, 30, TimeUnit.MINUTES);
        return typeList;
    }
}

